<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

</body>
<script>

  // 普通数据源：
  var arr = [
    { id: '1', name: '北京', pid: '' },

    { id: '11', name: '朝阳', pid: '1' },

    { id: '111', name: '朝阳群众1', pid: '11' },
    { id: '112', name: '朝阳群众2', pid: '11' },

    { id: '12', name: '顺义', pid: '1' },

    { id: '121', name: '顺义群众1', pid: '12' },
    { id: '122', name: '顺义群众2', pid: '12' },

    { id: '2', name: '深圳', pid: '' },

    { id: '21', name: '南山', pid: '2' },

    { id: '211', name: '南山群众1', pid: '21' },
    { id: '212', name: '南山群众2', pid: '21' },

    { id: '22', name: '宝安', pid: '2' },
    
    { id: '221', name: '宝安群众1', pid: '22' },
    { id: '222', name: '宝安群众2', pid: '22' }
  ]

  // 定义一个方法，使用递归来转换数据
  function turnData(arr, pid) {
    // 定义一个新的数组
    var newArr = []
    arr.forEach(item => {
      if (item.pid === pid) {
        var children = turnData(arr, item.id)
        item.children = children
        newArr.push(item)
      }
    })
    // 返回给外界
    return newArr
  }
  var result = turnData(arr, '')
  console.log(result);

</script>

</html>